<template>
  <e-container :loading="loading">
    <e-title title="Financial Settings" />
    <a-divider />
    <div class="form">
      <a-form ref="formRef" :model="apiData" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item class="bordered" label="Payment Option" name="paymentMethod">
              <a-select
                v-model:value="paymentMethodWrapped"
                show-search
                option-filter-prop="label"
                option-label-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in dict.paymentMethods" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="isAdvance">
              <template #label>
                <e-field-tooltip
                  filed-name="Prepayment"
                  tips="Specifies whether the account is a pre-payment account; If yes, pre-payment account will be used as a virtual wallet, and project invoices would deduct directly from the prepaid amount."
                />
              </template>
              <e-radio v-model="apiData.isAdvance" :options="options" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item name="isMonthPayment">
              <template #label>
                <e-field-tooltip
                  filed-name="Monthly Combined Invoice"
                  tips="Specifies whether to aggregate invoices on a monthly basis; If yes, the approved invoices will be aggregated and managed monthly, and Finance would send a combined invoice for the month."
                />
              </template>
              <e-radio v-model="apiData.isMonthPayment" :options="options" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="isInvoiceFileDate">
              <template #label>
                <e-field-tooltip
                  filed-name="Month-End Invoice Date"
                  tips="Specifies whether to generate the invoices at the month-end; If yes, the invoice will be generated and dated as of month-end."
                />
              </template>
              <e-radio v-model="apiData.isInvoiceFileDate" :options="options" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item name="isEleInvoice">
              <template #label>
                <e-field-tooltip
                  filed-name="Electronic Invoice (Send Email)"
                  tips="Specifies whether to generate electronic invoice; typically yes for non-PRC clients."
                />
              </template>
              <e-radio v-model="apiData.isEleInvoice" :options="options" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="isAutoSentInvoice">
              <template #label>
                <e-field-tooltip
                  filed-name="Auto-send Invoice"
                  tips="Specifies whether to automatically send the invoice once approved."
                />
              </template>
              <e-radio v-model="apiData.isAutoSentInvoice" :options="options" @change="handleIsAutoSentInvoiceChange" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item name="isOnlineInvoice">
              <template #label>
                <e-field-tooltip
                  filed-name="Online Invoice (via client preferred portal)"
                  tips="Specifies whether to upload the invoice using a client portal. Typically no, unless otherwise specified by client."
                />
              </template>
              <e-radio v-model="apiData.isOnlineInvoice" :options="options" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="isPaperInvoice">
              <template #label>
                <e-field-tooltip
                  filed-name="Taxation Invoice"
                  tips="Specifies whether to send a taxation invoice. Typically no, unless for a PRC client.VAT invoices should be send paper."
                />
              </template>
              <a-select
                v-model:value="apiData.isPaperIn"
                show-search
                option-filter-prop="label"
                option-label-prop="label"
                :get-popup-container="triggerNode => triggerNode.parentNode"
              >
                <a-select-option v-for="item in paperTypeOptions" :key="item.value" :label="item.text">
                  {{ item.text }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item name="isReminder">
              <template #label>
                <e-field-tooltip
                  filed-name="Payment Reminder"
                  tips="Specifies whether acceptable to send payment reminder."
                />
              </template>
              <e-radio v-model="apiData.isReminder" :options="options" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="isAutoReminder">
              <template #label>
                <e-field-tooltip
                  filed-name="Auto-send Reminder"
                  tips="Specifies whether to automatically send payment reminder for invoices past due by 45 days. Sent every month on the 21st."
                />
              </template>
              <e-radio v-model="apiData.isAutoReminder" :options="options" @change="handleIsAutoReminderChange" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Tax Rate (%)" name="clientTax">
              <a-input-number
                v-model:value="apiData.clientTax"
                :min="0"
                :max="100"
                :precision="0"
                autocomplete="off"
                style="width: 100%"
                addon-after="%"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="External Invoice Note" name="customize">
              <a-textarea v-model:value="apiData.customize" autocomplete="off" style="min-height: 80px" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Internal Invoice Note" name="invoiceDemand">
              <a-textarea v-model:value="apiData.invoiceDemand" autocomplete="off" style="min-height: 80px" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleCancel">Cancel</a-button>
        <a-button v-permission="'FinancialInformation:Basic:Edit'" type="primary" @click="handleSave">Save</a-button>
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { ref, reactive, computed, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { CONFIRM_BACK_TO_DETAIL, CONFIRM_FINANCIAL_SEND, SAVED_SUCCESSFULLY } from '@/constants/message.js'
import financial from '@/api/client/financial.js'
import BasicInfo from '@/api/client/basicInfo.js'
import EContainer from '@/components/EContainer.vue'
import ETitle from '@/components/ETitle.vue'
import ERadio from '@/components/ERadio.vue'
import EFieldTooltip from '@/components/EFieldTooltip.vue'
import { useDictNullValue } from '@/hooks/useDictNullValue.js'

const route = useRoute()
const router = useRouter()
const store = useStore()
const emits = defineEmits(['updated'])
const loading = ref(true)
const { id } = route.params
const gutter = [120, 16]
const { Modal, message } = inject('Feedback')
const briefInfo = computed(() => store.state.client.briefInfo)
const apiData = reactive({
  paymentMethod: 0,
  isAdvance: false,
  isMonthPayment: false,
  isInvoiceFileDate: false,
  isEleInvoice: false,
  isAutoSentInvoice: false,
  isOnlineInvoice: false,
  isPaperInvoice: false,
  isPaperIn: 0,
  paperInvoiceType: 0,
  paperInvoiceTypeName: 0,
  clientTax: 0,
  isReminder: false,
  isAutoReminder: false,
  customize: '',
  invoiceDemand: ''
})
const paymentMethodWrapped = useDictNullValue(apiData, 'paymentMethod')
const formRef = ref(null)
const dict = ref(computed(() => store.state.dict))
const paperTypeOptions = ref([])
const options = [
  { text: 'Yes', value: true },
  { text: 'No', value: false }
]
const rules = {}
if (briefInfo.value.isExisting) {
  rules.clientTax = [
    {
      required: true,
      // whitespace: true,
      message: 'Please input Tax Rate'
    }
  ]
}
store.dispatch('dict/getPaymentMethods')
// Tier1客户选择自动发送或自动催款时候确认提示
const handleIsAutoSentInvoiceChange = val => {
  if (val) {
    BasicInfo.getInfo(id).then(({ data }) => {
      if (data.clientTier === 1) {
        Modal.confirm({
          content: CONFIRM_FINANCIAL_SEND,
          onCancel: () => {
            apiData.isAutoSentInvoice = false
          }
        })
      }
    })
  }
}
const handleIsAutoReminderChange = val => {
  if (val) {
    BasicInfo.getInfo(id).then(({ data }) => {
      if (data.clientTier === 1) {
        Modal.confirm({
          content: CONFIRM_FINANCIAL_SEND,
          onCancel: () => {
            apiData.isAutoReminder = false
          }
        })
      }
    })
  }
}
/**
 * 回显数据
 */
const review = () => {
  financial
    .getPaperInvoiceType()
    .then(res => {
      if (res.code === 2000) {
        paperTypeOptions.value = res.data
      }
    })
    .then(() => {
      financial
        .getBasicInfo(id)
        .then(res => {
          if (res.code === 2000) {
            let i = 0
            paperTypeOptions.value.forEach(item => {
              if (res.data.paperInvoiceTypeName === item.text) {
                apiData.isPaperIn = item.value
                i++
              }
            })
            if (i === 0) {
              apiData.isPaperIn = undefined
            }
            apiData.paymentMethod = res.data.paymentMethod || undefined
            apiData.isAdvance = res.data.isAdvance
            apiData.isMonthPayment = res.data.isMonthPayment
            apiData.isInvoiceFileDate = res.data.isInvoiceFileDate
            apiData.isEleInvoice = res.data.isEleInvoice
            apiData.isAutoSentInvoice = res.data.isAutoSentInvoice
            apiData.isOnlineInvoice = res.data.isOnlineInvoice
            apiData.isPaperInvoice = res.data.isPaperInvoice
            apiData.paperInvoiceTypeName = res.data.paperInvoiceTypeName
            apiData.isReminder = res.data.isReminder
            apiData.isAutoReminder = res.data.isAutoReminder
            apiData.clientTax = res.data.clientTax || res.data.clientTax === 0 ? res.data.clientTax * 100 : undefined
            apiData.customize = res.data.externalNote
            apiData.invoiceDemand = res.data.internalNote
          }
        })
        .finally(() => {
          loading.value = false
        })
    })
}
/**
 * 保存
 */
const handleSave = () => {
  formRef.value.validate().then(() => {
    save()
  })
}
/**
 * 封装保存方法
 */
const save = () => {
  apiData.isPaperInvoice = apiData.isPaperIn !== 0
  apiData.paperInvoiceType = apiData.isPaperIn
  financial
    .updateClientFinanceInfo({
      id,
      paymentMethod: apiData.paymentMethod,
      isMonthPayment: apiData.isMonthPayment,
      isEleInvoice: apiData.isEleInvoice,
      isAutoSentInvoice: apiData.isAutoSentInvoice,
      isPaperInvoice: apiData.isPaperInvoice,
      paperInvoiceType: apiData.paperInvoiceType,
      isOnlineInvoice: apiData.isOnlineInvoice,
      isAdvance: apiData.isAdvance,
      isUrge: apiData.isReminder,
      isAutoReminder: apiData.isAutoReminder,
      isInvoiceFileDate: apiData.isInvoiceFileDate,
      clientTax: apiData.clientTax || apiData.clientTax === 0 ? apiData.clientTax / 100 : null,
      customize: apiData.customize ? apiData.customize.trim() : '',
      invoiceDemand: apiData.invoiceDemand ? apiData.invoiceDemand.trim() : ''
    })
    .then(res => {
      if (res.code === 2000) {
        message.success(SAVED_SUCCESSFULLY)
        router.push({ name: 'Financial Information' })
        emits('updated')
      }
    })
}
/**
 * 返回
 */
const handleCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      router.push({ name: 'Financial Information' })
      emits('updated')
    }
  })
}
/**
 * 初始化
 */
review()
</script>

<style lang="less" scoped>
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
:deep(.ant-divider) {
  border-top: 1px solid #dcdee7 !important;
}
:deep(.ant-input-number-handler-wrap) {
  display: none !important;
}
:deep(.ant-input),
:deep(.ant-select),
:deep(.ant-input-number),
:deep(.ant-select:not(.ant-select-customize-input) .ant-select-selector) {
  border-color: @border-color !important;
}
:deep(.ant-form-item-has-error .ant-input-number),
:deep(.ant-form-item-has-error .ant-input-affix-wrapper),
:deep(.ant-form-item-has-error .ant-input-number:hover),
:deep(.ant-form-item-has-error .ant-input-affix-wrapper:hover) {
  border-color: #fc4b3b !important;
}
</style>
<route lang="yaml">
name: Financial Settings
path: '/client/:id/financial-information/financial-settings'
meta:
  title: Financial Settings
  permission: FinancialInformation
</route>
